import { axiosMock, delayFn, randArrItem } from '@/services/axiosMock'
import { DEFAULT_PAGE_SIZE } from '@/utils/pagination'
import type {
  Gender,
  IAddressInfoReq,
  IAddressInfoRes,
  ISetBatchPublishEventReq,
  ISetBatchPublishFirstLegInformationReq,
  ISetBatchPublishLastLegInformationReq,
  ISetBatchPublishLogisticsChannelReq,
  ISetPublishEventReq,
  IStaffInfo,
  IWaybillRecordItem,
  IWaybillRecordListRes,
  IWaybillRecordTabCountRes,
} from '../interface'

const TOTAL = 250

// 统一的批量操作响应数据结构类型
type IBatchActionResultItem = {
  waybillNo: string
  success: boolean
  message: string
  eventId?: number
}
type IBatchActionSummary = {
  totalCount: number
  successCount: number
  failCount: number
  results: IBatchActionResultItem[]
}

const createStaff = (id: number): IStaffInfo => {
  return {
    staffType: randArrItem([1, 2, 3, 4], 0.2) || undefined,
    user: {
      active: true,
      avatar: undefined,
      createdDate: Date.now(),
      departmentId: randArrItem([101, 102, 103], 0.3) || undefined,
      englishName: randArrItem(['Alice', 'Bob', 'Charlie'], 0.2) || undefined,
      gender: randArrItem(['MAN', 'WOMAN', 'UNKNOWN'] as const) as Gender | undefined,
      id: id,
      loginDate: Date.now(),
      name: randArrItem(['张三', '李四', '王五']),
      num: `NO${String(id).padStart(5, '0')}`,
      password: undefined,
      phone: randArrItem(['13800000000', '13900000001'], 0.3) || undefined,
      position: randArrItem(['业务员', '跟单员', '操作'], 0.3) || undefined,
      roleId: randArrItem([1, 2, 3], 0.3) || undefined,
      username: randArrItem(['alice', 'bob', 'charlie'], 0.3) || undefined,
    },
  }
}

const createItem = (num: number): IWaybillRecordItem => {
  const waybillNo = `LH${String(20241116)}${String(num).padStart(4, '0')}`
  const eta = randArrItem(['11-18', '11-19', '11-20'], 0.3) || undefined
  const etd = randArrItem(['11-10', '11-11', '11-12'], 0.3) || undefined
  const signingTime = randArrItem(['11-24', '11-25'], 0.1) || undefined
  const shipmentDate = randArrItem(['11-10', '11-12', '11-14'])
  const destinationCountry = randArrItem(['中国', '美国', '加拿大'], 0.2) || undefined
  const latestEventEn = randArrItem(['Departed origin', 'Arrived at port', 'In transit'], 0.2) || undefined
  const latestEventTime = randArrItem(['11-15 10:00', '11-16 08:30'], 0.2) || undefined
  const logisticsChannelName = randArrItem(['海运', '空运', '铁路', '卡车'])
  const logisticsChannelMerchantServers = randArrItem(['Vendor A', 'Vendor B', 'Vendor C'], 0.2) || undefined

  return {
    age: randArrItem(['5', '12', '20']),
    boxNum: randArrItem(['10', '24', '36'], 0.2) || undefined,
    containerNumber: randArrItem([`CONT${String(num).padStart(4, '0')}`, undefined]),
    customer: randArrItem(['Amazon FBA', 'Walmart', 'Target', 'Best Buy']),
    destinationCode: randArrItem(['SEA', 'LAX', 'JFK'], 0.2) || undefined,
    destinationCountry,
    eta,
    etd,
    fbaId: randArrItem([`FBA${num}`, undefined]),
    latestEventEn,
    latestEventTime,
    logisticsChannelName,
    logisticsChannelMerchantServers,
    messageType: randArrItem([1, 2, 3], 0.2) || undefined,
    nextUpdateTime: randArrItem(['2025-11-16 09:00', '2025-11-17 14:00'], 0.3) || undefined,
    nextUpdateTimeRemind: randArrItem([1, 2, 3, 4, 5], 0.2) || undefined,
    scheduledDeliveryTimeSlot: randArrItem(['08:00-12:00', '12:00-16:00'], 0.2) || undefined,
    shipmentDate,
    shipTrackStatus: randArrItem([1, 2, 3]),
    signingTime,
    staffInfoList: randArrItem([
      Array(2)
        .fill(null)
        .map((_i, idx) => createStaff(num * 10 + idx)),
      undefined,
    ]),
    vesselName: randArrItem(['Evergreen', 'Maersk', 'COSCO'], 0.3) || undefined,
    voyageNumber: randArrItem([`V${1000 + num}`, undefined]),
    waybillNo,
    waybillStatus: randArrItem([1, 2, 3, 4, 5, 6, 7, 8, 9]),
  }
}

axiosMock('default', mock => {
  // 获取运单列表
  mock.onPost(`/tmsapi/waybill_record_v2/list`).reply(
    delayFn<IWaybillRecordListRes>(600, ({ data }) => {
      const size = +data.size || DEFAULT_PAGE_SIZE
      const page = +data.page || 1

      const records: IWaybillRecordItem[] = Array(size)
        .fill(null)
        .map((_item, index) => {
          const num = (page - 1) * size + index + 1
          return createItem(num)
        })

      return {
        success: true,
        data: {
          current: page,
          pages: Math.ceil(TOTAL / size),
          records,
          size,
          total: TOTAL,
        },
      }
    }),
  )

  // 获取页签统计
  mock.onPost(`/tmsapi/waybill_record_v2/tab/count`).reply(
    delayFn<IWaybillRecordTabCountRes>(400, () => {
      const perTab = Math.floor(TOTAL / 9)
      const data = Array.from({ length: 10 }).map((_v, tabId) => ({
        tabId,
        count: tabId === 0 ? TOTAL : perTab + (tabId % 3),
      }))
      return {
        success: true,
        data,
      }
    }),
  )

  // 批量设置发布事件
  mock.onPost(`/tmsapi/waybill_record_v2/batch/set/publish_event`).reply(
    delayFn<IBatchActionSummary>(800, ({ data }) => {
      const req = data as ISetBatchPublishEventReq
      const publishEvents = req.publishPathIDTOS || []

      // 模拟处理结果
      const results = publishEvents.map((event: ISetPublishEventReq) => ({
        waybillNo: event.waybillNo ?? '',
        success: Math.random() > 0.1, // 90% 成功率
        message: Math.random() > 0.1 ? '事件发布成功' : '事件发布失败：网络异常',
        eventId: Math.floor(Math.random() * 10000) + 1000,
      }))

      const successCount = results.filter(r => r.success).length
      const failCount = results.length - successCount

      return {
        success: true,
        data: {
          totalCount: results.length,
          successCount,
          failCount,
          results,
        },
      }
    }),
  )

  // 批量设置物流渠道
  mock.onPost(`/tmsapi/waybill_record_v2/batch/set/logistics_channel`).reply(
    delayFn<IBatchActionSummary>(600, ({ data }) => {
      const req = data as ISetBatchPublishLogisticsChannelReq
      const channels = req.logisticChannelSetIDTOS || []

      const results = channels.map(channel => ({
        waybillNo: channel.waybillNo ?? '',
        success: Math.random() > 0.05, // 95% 成功率
        message: Math.random() > 0.05 ? '物流渠道更新成功' : '物流渠道更新失败：参数错误',
      }))

      const successCount = results.filter(r => r.success).length
      const failCount = results.length - successCount

      return {
        success: true,
        data: {
          totalCount: results.length,
          successCount,
          failCount,
          results,
        },
      }
    }),
  )

  // 批量设置第一程信息
  mock.onPost(`/tmsapi/waybill_record_v2/batch/set/first_leg_information`).reply(
    delayFn<IBatchActionSummary>(700, ({ data }) => {
      const req = data as ISetBatchPublishFirstLegInformationReq
      const firstLegs = req.firstLegInformationSetIDTOS || []

      const results = firstLegs.map(firstLeg => ({
        waybillNo: firstLeg.waybillNo ?? '',
        success: Math.random() > 0.08, // 92% 成功率
        message: Math.random() > 0.08 ? '第一程信息更新成功' : '第一程信息更新失败：承运商信息有误',
      }))

      const successCount = results.filter(r => r.success).length
      const failCount = results.length - successCount

      return {
        success: true,
        data: {
          totalCount: results.length,
          successCount,
          failCount,
          results,
        },
      }
    }),
  )

  // 批量设置最后程信息
  mock.onPost(`/tmsapi/waybill_record_v2/batch/set/last_leg_information`).reply(
    delayFn<IBatchActionSummary>(650, ({ data }) => {
      const req = data as ISetBatchPublishLastLegInformationReq
      const lastLegs = req.lastLegInformationSetIDTOS || []

      const results = lastLegs.map(lastLeg => ({
        waybillNo: lastLeg.waybillNo ?? '',
        success: Math.random() > 0.06, // 94% 成功率
        message: Math.random() > 0.06 ? '最后程信息更新成功' : '最后程信息更新失败：运单号不存在',
      }))

      const successCount = results.filter(r => r.success).length
      const failCount = results.length - successCount

      return {
        success: true,
        data: {
          totalCount: results.length,
          successCount,
          failCount,
          results,
        },
      }
    }),
  )

  // 批量获取运单地址信息
  mock.onPost(`/tmsapi/waybill_record_v2/addressInfo`).reply(
    delayFn<IAddressInfoRes[]>(600, ({ data }) => {
      const req = (data || {}) as IAddressInfoReq
      const list = req.publishPathIDTOS || []

      const res: IAddressInfoRes[] = list.map(item => {
        const city = randArrItem(['Dongguan', 'Shanghai', 'Los Angeles', 'New York'])
        const countryCode = randArrItem(['CN', 'US', 'CA'])
        const countryMap: Record<string, string> = { CN: '中国', US: '美国', CA: '加拿大' }
        const codeMap: Record<string, string> = {
          Dongguan: 'DG',
          Shanghai: 'SH',
          'Los Angeles': 'LA',
          'New York': 'NY',
        }
        const englishMap: Record<string, string> = {
          Dongguan: 'LinkHub Dongguan Warehouse',
          Shanghai: 'Shanghai Port',
          'Los Angeles': 'Los Angeles Airport',
          'New York': 'New York Port',
        }
        const chineseMap: Record<string, string> = {
          Dongguan: '领赫东莞仓',
          Shanghai: '上海港',
          'Los Angeles': '洛杉矶机场',
          'New York': '纽约港',
        }

        return {
          waybillNo: item.waybillNo,
          addressListODTO: {
            addressId: Math.floor(Math.random() * 100000),
            addressType: randArrItem([1, 2, 3, 4, 5]),
            chineseName: chineseMap[city!],
            englishName: englishMap[city!],
            city,
            code: codeMap[city!],
            contacts: randArrItem(['Jason', 'Alice', 'Bob'], 0.4) || undefined,
            country: countryMap[countryCode!],
            countryCode,
            email: randArrItem(['ops@linkhub.com', 'service@linkhub.com'], 0.3) || undefined,
            phone: randArrItem(['13800000000', '13900000001'], 0.3) || undefined,
            postalCode: randArrItem(['523000', '90001', '10001'], 0.3) || undefined,
            stateProvince: randArrItem(['Guangdong', 'Shanghai', 'California', 'New York']),
            street1: randArrItem(['No.1 Warehouse Rd', '500 Harbor Blvd', '100 Main St']),
            street2: randArrItem(['Room 101']),
            isCommon: randArrItem([0, 1]),
          },
        }
      })

      return {
        success: true,
        data: res,
      }
    }),
  )
})
